package vn.ikame.android.boojtran.truyenbua;

import java.util.ArrayList;

import vn.ikame.android.boojtran.truyenbua.download.ItemListDowloadListener;
import vn.ikame.android.boojtran.truyenbua.download.ItemListDownload;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import vn.ikame.android.boojtran.truyenbua.utility.CConstant;
import vn.ikame.android.boojtran.truyenbua.utility.ItemManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.AbsListView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class ListItem extends SuperActivity implements
		AbsListView.OnScrollListener, ItemListDowloadListener {
	private ListView listview;
	private MenuListAdapter adapter;
	private AdView adView;
	public static ListItem menu;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		// if (init) {
		// init = false;
		// GA.startDetail(this);
		// GA.trackDetailView(APP_NAME);
		// }
		if (ItemManager.getInstance().getListItem() == null
				|| ItemManager.getInstance().getListItem().size() <= 0) {
			startActivity(new Intent(ListItem.this, Splash.class));
			this.finish();
		} else {
			initView();
			// admob
			adView = (AdView) this.findViewById(R.id.adView);
			adView.loadAd(new AdRequest());
			menu = this;

			if (store.isFirstTime()) {
				store.setFirstTime(false);
				GA.trackDetailView(APP_NAME + "_installApp");
				showAboutDialog();
			}

			if (!isShowWifiWarning && !isWifiConnected()) {
				isShowWifiWarning = true;
				showInfoDialog(
						"Kết nối",
						"Bạn nên sử dụng kết nối wifi để tải ảnh nhanh hơn và tiết kiệm dung lượng 3G. Chúc bạn vui vẻ!");
			}
		}
	}

	private void initView() {
		if (ItemManager.getInstance().getListItem() == null
				|| ItemManager.getInstance().getListItem().size() <= 0) {
			startActivity(new Intent(ListItem.this, Splash.class));
			this.finish();
		} else {
			listview = (ListView) findViewById(R.id.list);
			adapter = new MenuListAdapter(this, R.layout.list_item, ItemManager
					.getInstance().getListItem());
			listview.setAdapter(adapter);
			listview.setOnScrollListener(this);
		}
	}

	private class MenuListAdapter extends ArrayAdapter<Item> {
		private ArrayList<Item> myList;
		private int textViewResourceId;

		public MenuListAdapter(Context context, int textViewResourceId,
				ArrayList<Item> list) {
			super(context, textViewResourceId, list);
			this.textViewResourceId = textViewResourceId;
			this.myList = list;
		}

		private View recycleOrCreateView(View v) {
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getContext()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(textViewResourceId, null);

				ViewHolder vh = new ViewHolder();
				vh.icon = (ImageView) v.findViewById(R.id.icon);
				vh.title = (TextView) v.findViewById(R.id.title);
				vh.subtitle = (TextView) v.findViewById(R.id.subtitle);
				vh.subtitle.setVisibility(View.GONE);
				v.setTag(vh);
			}
			v.setBackgroundResource(R.drawable.row_item_odd);
			return v;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View view = recycleOrCreateView(convertView);
			ViewHolder vh = (ViewHolder) view.getTag();
			if (position < myList.size()) {
				vh.icon.setImageResource(R.drawable.new_icon);
				vh.title.setTextColor(getResources().getColor(R.color.white));
				if (isBelongIntArray(showedArr, myList.get(position).getId())) {
					vh.title.setTextColor(getResources().getColor(
							R.color.light_blue));
					vh.icon.setImageResource(R.drawable.laugh_icon);
				}
				vh.title.setText(myList.get(position).getTitle()); // (myList.size()
																	// -
																	// position)
																	// + ". "+
				if (position % 2 == 0)
					view.setBackgroundResource(R.drawable.row_item_even);
				// vh.subtitle.setText(myList.get(position).getSize());
				view.setTag(vh);
			}
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					ItemManager.getInstance().setCurItem(position);
					if (!isBelongIntArray(showedArr, myList.get(position)
							.getId())) {
						showedArr.add(myList.get(position).getId());
						store.setShowedArr(showedArr);
					}
					// Menu.this.finish();
					startActivity(new Intent(ListItem.this, Viewer.class));
				}
			});
			return view;
		}

		private class ViewHolder {
			ImageView icon;
			TextView title;
			TextView subtitle;
		}

	}

	@Override
	protected void onResume() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
		GA.trackDetailView(APP_NAME);
		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			createExitMessage();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void createExitMessage() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage("Bạn có muốn thoát ứng dụng?");
		alert.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if (noti.getType() == 3 && !noti.isShow()) {
					createNotificationAlert();
				} else {
					ListItem.this.finish();
					System.gc();
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			}
		});

		alert.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (previousTotal == totalItem)
			return;
		if (loading) {
			if (totalItemCount > previousTotal) {
				loading = false;
				previousTotal = totalItemCount;
			}
		}

		if (!loading
				&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
			requestListItems(CConstant.SVR_IMG_LINK, previousTotal, itemCount);
			loading = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	protected void requestListItems(String svr_link, int start, int count) {
		if (isOnline()) {
			ItemListDownload itemListDownload = new ItemListDownload(this, this);
			itemListDownload.start(svr_link, start, count);
		} else {
			showNetworkDialog();
		}
	}

	@Override
	public void onDownloadFinish(ArrayList<Item> result, String svr_link,
			int start, int count) {
		if (result != null && result.size() > 0) {
			Log.e("TAG", "ok:" + result.size());
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				if (gotoBookmark) {
					previousTotal = result.size();
					gotoBookmark = false;
					ItemManager.getInstance().getListItem().clear();
					ItemManager.getInstance().getListItem().addAll(result);
					adapter.notifyDataSetChanged();
					int pic = getArrIndex(ItemManager.getInstance()
							.getListItem(), store.getPic());
					if (pic != -1) {
						ItemManager.getInstance().setCurItem(pic);
						if (!isBelongIntArray(showedArr, ItemManager
								.getInstance().getItem(pic).getId())) {
							showedArr.add(ItemManager.getInstance()
									.getItem(pic).getId());
							store.setShowedArr(showedArr);
						}
						startActivity(new Intent(ListItem.this, Viewer.class));
					}
				} else {
					ItemManager.getInstance().getListItem().addAll(result);
					adapter.notifyDataSetChanged();
				}
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				Log.e("TAG", "ok2");
				funStories = result;
				startActivity(new Intent(ListItem.this, FunStory.class));
			}
		} else {
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				GA.trackDetailView(APP_NAME + "_downloadListError");
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				if (result.size() <= 0) {
					storyArr.clear();
					store.setStoryArr(storyArr);
					if (funStories == null || funStories.size() <= 0) {
						requestListItems(CConstant.SVR_FUNSTORY_LINK, 0,
								itemCount);
					} else {
						startActivity(new Intent(ListItem.this, FunStory.class));
					}
				} else {
					GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
					Log.e("TAG", "lose2");
				}
			}
			showReconnectDialog(svr_link, start, count);
			Log.e("TAG", "lose");
		}
	}

	@Override
	public void onDownloadError(String svr_link, int start, int count) {
		if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
			GA.trackDetailView(APP_NAME + "_downloadListError");
		} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
			GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
		}
		showReconnectDialog(svr_link, start, count);
	}
}
